﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using KPIS.GERP.Models;
using KPIS.GERP.Models.HRM;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.Models.SYS.ViewModel;
using System.Data.Entity;

namespace KPIS.GERP.WCF.SYS
{
    [ServiceContract]
    public interface ISysSearchService
    {
        [OperationContract]
        SearchResult SelectSearch(SearchCriteriaVM searchCriteriaVm, out string errorMessage);

        [OperationContract]
        SearchResult SelectSearchFast(string keyword, out string errorMessage);

        [OperationContract]
        SearchResult SelectSearchResult(int searchId);
    }

    public class SysSearchService : ISysSearchService
    {
        #region Implementation of ISysSearchService

        private List<Employee> employees;

        public SearchResult SelectSearch(SearchCriteriaVM searchCriteriaVm, out string errorMessage)
        {
            return SelectSearchCore(searchCriteriaVm, out errorMessage);
        }

        public SearchResult SelectSearchFast(string keyword, out string errorMessage)
        {
            return SelectSearchCore(new SearchCriteriaVM
                {
                    SearchKeyword = keyword,
                    SeachOption = SeacrhOptionEnum.ทั้งหมด,
                    SortResultByType = SortResultByTypeEnum.วันที่,
                    SortResultOrdering = SortResultOrderingEnum.มากไปน้อย
                }, out errorMessage);
        }

        public SearchResult SelectSearchResult(int searchId)
        {
            using (var db = new GERPContext())
            {
                return db.SearchResults.Include(o => o.SearchResultDtls).FirstOrDefault(o => o.SearchId == searchId);
            }
        }

        private SearchResult SelectSearchCore(SearchCriteriaVM model, out string errorMessage)
        {
            using (var db = new GERPContext(true))
            {
                /* Disabled 
                // Get recently result matched
                var searchResultRecentlyMatched = db.SearchResults.Include(o => o.SearchResultDtls).ToList()
                    .Where(o => o.RecordStatus != "D" &&
                                o.SearchKeyword == model.SearchKeyword &&
                                o.SearchTitleOnly == model.SearchTitleOnly &&
                                o.SearchByEmployeeName == model.SearchByEmployeeName &&
                                o.SearchByEmployeeNameExactName == model.SearchByEmployeeNameExactName &&
                                o.ExpireSearchResult >= DateTime.Now &&
                                o.SeacrhOption == model.SeachOption &&
                                o.SortResultByType == model.SortResultByType &&
                                o.SortResultOrdering == model.SortResultOrdering)
                    .OrderByDescending(o => o.SearchId).FirstOrDefault();
                if (searchResultRecentlyMatched != null)
                {
                    errorMessage = null;
                    return searchResultRecentlyMatched;
                }
                 */

                // Not found recently match, make new search
                var searchResult = new SearchResult();
                searchResult.SearchKeyword = model.SearchKeyword;
                searchResult.SearchTitleOnly = model.SearchTitleOnly;
                searchResult.SearchByEmployeeName = model.SearchByEmployeeName;
                searchResult.SearchByEmployeeNameExactName = model.SearchByEmployeeNameExactName;
                searchResult.SeacrhOption = model.SeachOption;
                searchResult.SortResultByType = model.SortResultByType;
                searchResult.SortResultOrdering = model.SortResultOrdering;
                searchResult.SearchResultDtls = new Collection<SearchResultDtl>();
                searchResult.CreatedBy = model.RequestByEmpId;
                searchResult.CreatedWhen = DateTime.Now;

                // Collect all data by Search Option
                List<SearchResultDtl> dtl = new List<SearchResultDtl>();
                if (model.SeachOption == SeacrhOptionEnum.ประเภทพัสดุ || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.MasResourceTypes.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.ResTypeId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Descr;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.ประเภทพัสดุ;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.หมวดพัสดุ || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.MasResourceGroups.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.ResGrpId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Descr;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.หมวดพัสดุ;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.กลุ่มพัสดุ || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.MasResourceSubGroups.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.ResSubGrpId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Descr;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.กลุ่มพัสดุ;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.รายการพัสดุ || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.MasResourceItems.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.ResItemId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Descr;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.รายการพัสดุ;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.แจ้งความประสงค์ || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.PrePurchaseRequests.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.PprId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Reason;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.แจ้งความประสงค์;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.รายการขอซื้อจ้าง || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.PurchaseRequests.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.PrId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Reason;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.รายการขอซื้อจ้าง;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.ใบสั่งงานสัญญา || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.PurchaseOrders.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.PoId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Descr;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.ใบสั่งงานสัญญา;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.รายการตรวจรับ || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.DeliveryNotes.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.DnId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Descr;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.รายการตรวจรับ;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.ระเบียบจัดซื้อจ้าง || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.MasPurchaseRegulars.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.RegularId;
                        resultDtl.DataCode = null;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Description;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.ระเบียบจัดซื้อจ้าง;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.หน่วยนับ || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.MasUnits.Where(o=>o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.UnitId;
                        resultDtl.DataCode = null;
                        resultDtl.DataName = data.Name;
                        resultDtl.DataDescription = data.Descr;
                        resultDtl.DataOtherText = null;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.หน่วยนับ;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                if (model.SeachOption == SeacrhOptionEnum.คำขออนุมัติ || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.Tasks.Where(o => o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.TaskId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.Code + " " + data.RefCode + " " + data.Title;
                        resultDtl.DataDescription = data.Remark;
                        resultDtl.DataOtherText = data.RefCode;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.คำขออนุมัติ;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }


                if (model.SeachOption == SeacrhOptionEnum.การลา || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    foreach (var data in db.PsAbsences.Where(o => o.RecordStatus != "D"))
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.AbsenceId;
                        resultDtl.DataCode = data.Code;
                        resultDtl.DataName = data.RequestTitle;
                        resultDtl.DataDescription = data.Description;
                        resultDtl.DataOtherText = data.ContactAddress;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.การลา;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }
                if (model.SeachOption == SeacrhOptionEnum.ทะเบียนผู้ขาย || model.SeachOption == SeacrhOptionEnum.ทั้งหมด)
                {
                    var db2 = new GERPContext(false);
                    foreach (var data in db2.MasContacts.Where(o => o.RecordStatus != "D").ToList())
                    {
                        var resultDtl = new SearchResultDtl();

                        resultDtl.DataId = data.ConId;
                        resultDtl.DataCode = null;
                        resultDtl.DataName = data.NameTh + " " + data.NameEng;
                        resultDtl.DataDescription = data.StatRemarks;
                        resultDtl.DataOtherText = "ที่อยู่" + data.Address + ", ";
                        resultDtl.DataOtherText += "อำเภอ" + data.Amphur + ", ";
                        resultDtl.DataOtherText += "ตึก" + data.Building + ", ";
                        resultDtl.DataOtherText += data.ConCategory + ", ";
                        resultDtl.DataOtherText += data.ContactGroup + ", ";
                        resultDtl.DataOtherText += data.ContactStatus + ", ";
                        resultDtl.DataOtherText += data.Coordinator + ", ";
                        resultDtl.DataOtherText += "ประเทศ" + data.Country + ", ";
                        resultDtl.DataOtherText += "เขต" + data.District + ", ";
                        resultDtl.DataOtherText += "อีเมล์/Email/E-mail" + data.Email + ", ";
                        resultDtl.DataOtherText += "Fax/แฟกซ์/โทรสาร" + data.Fax + ", ";
                        resultDtl.DataOtherText += data.FaxNext + ", ";
                        resultDtl.DataOtherText += "ชั้น" + data.Floor + ", ";
                        resultDtl.DataOtherText += "รหัส GFMIS " + data.GfmisCode + ", ";
                        resultDtl.DataOtherText += data.Lane + ", ";
                        resultDtl.DataOtherText += data.Postal + ", ";
                        resultDtl.DataOtherText += "จังหวัด" + data.Province + ", ";
                        resultDtl.DataOtherText += data.RegistedCapital + ", ";
                        resultDtl.DataOtherText += data.RegistedDate + ", ";
                        resultDtl.DataOtherText += "ถนน" + data.Road + ", ";
                        resultDtl.DataOtherText += data.StatRemarks + ", ";
                        resultDtl.DataOtherText += data.TaxCode + ", ";
                        resultDtl.DataOtherText += "โทรศัพท์" + data.Tel + ", ";
                        resultDtl.DataOtherText += data.TelNext + ", ";
                        resultDtl.DataOtherText += data.VatType + ", ";
                        resultDtl.DataOtherText += data.Village;
                        resultDtl.DataSiteNavigatePath = null; // gen on view
                        resultDtl.DataFileImageUrl = null; // gen on view
                        resultDtl.DataSeacrhOptionEnum = SeacrhOptionEnum.ทะเบียนผู้ขาย;

                        resultDtl.DataRecordStatus = data.RecordStatus;
                        resultDtl.DataCreatedBy = data.CreatedBy;
                        resultDtl.DataCreatedWhen = data.CreatedWhen;
                        resultDtl.DataCreatedByFullName = FindFullName(data.CreatedBy);
                        resultDtl.DataUpdatedBy = data.UpdatedBy;
                        resultDtl.DataUpdatedWhen = data.UpdatedWhen;
                        resultDtl.DataUpdatedByFullName = FindFullName(data.UpdatedBy);

                        dtl.Add(resultDtl);
                    }
                }

                //Filter data
                foreach(var data in dtl)
                {
                    // check is search by employee
                    bool found = false;
                    if(searchResult.SearchByEmployeeNameUsing)
                    {
                        var employeeNameOfDtl = data.DataCreatedByFullName + data.DataUpdatedByFullName;
                        if (!string.IsNullOrWhiteSpace(employeeNameOfDtl))
                        {
                            employeeNameOfDtl = employeeNameOfDtl.ToLower();
                            foreach (var partOfFullName in searchResult.SearchByEmployeeName.SplitBySpaceExcludeEmpty())
                            {
                                if (searchResult.SearchByEmployeeNameExactName)
                                {
                                    if (employeeNameOfDtl.SplitBySpaceExcludeEmpty().Any(partOfKeywordEmployeeName =>
                                                                                         partOfKeywordEmployeeName == partOfFullName))
                                    {
                                        data.ScoreCount = 10;
                                        searchResult.SearchResultDtls.Add(data);
                                        found = true;
                                        break;
                                    }
                                }
                                else if (employeeNameOfDtl.SplitBySpaceExcludeEmpty().Any(partOfKeywordEmployeeName =>
                                                                                          partOfKeywordEmployeeName.Contains(partOfFullName)
                                                                                          || partOfFullName.Contains(partOfKeywordEmployeeName)))
                                {
                                    data.ScoreCount = 10;
                                    searchResult.SearchResultDtls.Add(data);
                                    found = true;
                                    break;

                                }
                            }
                        }
                    }

                    // Remarks: if input employee name search, must found that employee result
                    if(!found && searchResult.SearchByEmployeeNameUsing) continue;

                    // Search title is for search code + title
                    string textToSearch = (searchResult.SearchTitleOnly ? data.DataName +" " + data.DataCode : data.AllText);

                    if (!textToSearch.ContainsAnyCaseInsensitive(searchResult.SearchKeywords.ToArray())) continue;

                    data.ScoreCount = textToSearch.CountStringOccurrences(searchResult.SearchKeywords.ToArray());
                    searchResult.SearchResultDtls.Add(data);
                }
                
                searchResult.ResultAmount = searchResult.SearchResultDtls.Count;

                // Ordering
                searchResult.SearchResultDtls = searchResult.SearchResultDtls.OrderByDescending(o => o.ScoreCount).ToList();

                if (model.SortResultOrdering == SortResultOrderingEnum.น้อยไปมาก)
                {
                    if (model.SortResultByType == SortResultByTypeEnum.ชื่อผู้ใช้งาน)
                    {
                        searchResult.SearchResultDtls = searchResult.SearchResultDtls
                            .OrderBy(o => o.DataCreatedByFullName)
                            .ThenBy(o => o.DataUpdatedByFullName)
                            .ToList();
                    }
                    else if (model.SortResultByType == SortResultByTypeEnum.วันที่)
                    {
                        searchResult.SearchResultDtls = searchResult.SearchResultDtls
                            .OrderBy(o => o.DataCreatedWhen)
                            .ThenBy(o => o.DataUpdatedWhen).ToList();
                    }
                    else if (model.SortResultByType == SortResultByTypeEnum.กระทู้)
                    {
                        searchResult.SearchResultDtls = searchResult.SearchResultDtls
                            .OrderBy(o => o.AllEmployee)
                            .ThenBy(o => o.AllText).ToList();
                    }
                }

                if (model.SortResultOrdering == SortResultOrderingEnum.มากไปน้อย)
                {
                    if (model.SortResultByType == SortResultByTypeEnum.ชื่อผู้ใช้งาน)
                    {
                        searchResult.SearchResultDtls = searchResult.SearchResultDtls
                            .OrderByDescending(o => o.DataCreatedByFullName)
                            .ThenByDescending(o => o.DataUpdatedByFullName).ToList();
                    }
                    else if (model.SortResultByType == SortResultByTypeEnum.วันที่)
                    {
                        searchResult.SearchResultDtls = searchResult.SearchResultDtls
                            .OrderByDescending(o => o.DataCreatedWhen)
                            .ThenByDescending(o => o.DataUpdatedWhen).ToList();
                    }
                    else if (model.SortResultByType == SortResultByTypeEnum.กระทู้)
                    {
                        searchResult.SearchResultDtls = searchResult.SearchResultDtls
                            .OrderByDescending(o => o.AllEmployee)
                            .ThenByDescending(o => o.AllText).ToList();
                    }
                }

                // Add to head, save to database
                db.SearchResults.Add(searchResult);
                // Remarks if data too much, may need clean this data.
                db.SaveChanges();

                if(string.IsNullOrWhiteSpace(model.SearchKeyword))
                {
                    errorMessage = "กรุณาระบุคำค้นหา";
                } else
                {
                    errorMessage = null;
                }
                return searchResult;
            }
        }

        //private int GetSearchFoundCount(string source, List<string> keyword)
        //{
        //    return 
        //}

        //private string GenAnchorMasResItem(int resItemId, string dtlCode, string dtlName)
        //{
        //    return string.Format(AnchorFormat, GenUrlMasResItem(resItemId), GenDtlText2(dtlCode, dtlName), "รายการพัสดุ");
        //}

        //private string GenAnchorMasResSubGroup(int resSubGrpId, string dtlCode, string dtlName)
        //{
        //    return string.Format(AnchorFormat, GenUrlMasResSubGroup(resSubGrpId), GenDtlText2(dtlCode, dtlName), "กลุ่มพัสดุ");
        //}

        //private string GenAnchorMasResGroup(int resGrpId, string dtlCode, string dtlName)
        //{
        //    return string.Format(AnchorFormat, GenUrlMasResGroup(resGrpId), GenDtlText2(dtlCode, dtlName), "หมวดพัสดุ");
        //}

        //private string GenAnchorMasResType(int resTypeId, string dtlCode, string dtlName)
        //{
        //    return string.Format(AnchorFormat, GenUrlMasResType(resTypeId), GenDtlText2(dtlCode, dtlName), "ประเภทพัสดุ");
        //}

        //private string GenUrlMasResItem(int resItemId)
        //{
        //    return string.Format("/MasResourceItem/Details/{0}", resItemId);
        //}

        //private string GenUrlMasResSubGroup(int resSubGrpId)
        //{
        //    return string.Format("/MasResourceSubGroup/Details/{0}", resSubGrpId);
        //}

        //private string GenUrlMasResGroup(int resGrpId)
        //{
        //    return string.Format("/MasResourceGroup/Details/{0}", resGrpId);
        //}

        //private string GenUrlMasResType(int resTypeId)
        //{
        //    return string.Format("/MasResourceType/Details/{0}", resTypeId);
        //}

        //private string GenDtlText(string typeText, string dtlCode, string dtlName)
        //{
        //    return string.Format("[{0}] {1} - {2}", typeText, dtlCode, dtlName);
        //}

        //private string GenDtlText2(string dtlCode, string dtlName)
        //{
        //    return string.Format("{0} - {1}", dtlCode, dtlName);
        //}

        private string FindFullName(int? empId)
        {
            if (!empId.HasValue) return string.Empty;
            if (employees == null) employees = new GERPContext().Employees.Where(o => o.RecordStatus != "D").ToList();

            var employee = employees.FirstOrDefault(o => o.EmpId == empId);
            return employee != null ? employee.FullName : string.Empty;
        }

        private const string Splitter = " <i class='icon-double-angle-right'></i> ";
        private const string AnchorFormat = "<a href='{0}' class='SearchResultNavPath' title='{2}'>{1}</a>";

        #endregion
    }
}